package fun.ticsmyc.question.stringQuestion;


import org.junit.Test;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author Ticsmyc
 * @date 2021-05-26 10:45
 */
public class 括号嵌套问题 {

    //leetcode 1190
    public String reverseParentheses(String s) {
        char[] str = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        Deque<String> stack = new LinkedList<>();
        for (int i = 0; i < str.length; ++i) {
            if(str[i] == '(') {
                stack.push(sb.toString());
                sb.setLength(0);
            } else if(str[i] == ')') {
                sb.reverse();
                sb.insert(0, stack.pop());
            } else {
                sb.append(str[i]);
            }
        }
        return sb.toString();

    }

    //leetcode 394 字符串解码
    public String decodeString(String s) {
        char[] str = s.toCharArray();
        int time =0;
        StringBuilder sb = new StringBuilder();
        Deque<String> stack = new LinkedList();
        Deque<Integer> t = new LinkedList();
        for(int i=0;i<str.length;++i){
            if(str[i]>='0' && str[i]<='9'){
                //数字
                time = time*10 + (str[i]-'0');
            }else if(str[i]=='['){
                stack.push(sb.toString());
                t.push(time);
                sb.setLength(0);
                time=0;
            }else if(str[i]==']'){
                time = t.pop();//sb这段的重复次数
                String repeat = sb.toString();
                for(int j=0;j<time-1;++j){
                    sb.append(repeat);
                }
                sb.insert(0,stack.pop());
                time =0;
            }else{
                sb.append(str[i]);
            }
        }
        return sb.toString();
    }

    @Test
    public void test(){
        System.out.println(decodeString("2[abc]3[cd]ef"));
    }
}
